package mybatis.web;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BaseServlet extends HttpServlet {
	protected static ApplicationContext applicationContext;
	static {
		applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("页面访问");
		String uri = request.getRequestURI();
		String methodName = uri.substring(uri.lastIndexOf("/")+1);
		System.out.println(methodName);
		Class clazz = this.getClass();
		Method method;
		try {
			method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			System.out.println(method.getName());
			System.out.println(this);
			method.invoke(this,request,response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}
	public void responseJson(HttpServletResponse response,Object obj) throws IOException {
		//
		response.setContentType("text/html;charset=utf-8");
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(), obj);
	}
}
